package com.bdtop.dbl.ui.activities.device;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bdtop.dbl.BaseActivity;
import com.bdtop.dbl.DBLApplication;
import com.bdtop.dbl.R;
import com.bdtop.dbl.model.DeviceInfo;
import com.bdtop.dbl.model.Position;
import com.bdtop.dbl.server.ServerApiFactory;
import com.bdtop.dbl.server.response.AddressResponse;
import com.bdtop.dbl.server.response.BaseResponse;
import com.bdtop.dbl.server.response.GetImgResponse;
import com.bdtop.dbl.thirdparty.asynchttp.RequestCallback;
import com.bdtop.dbl.ui.activities.main.MainActivity;
import com.bdtop.dbl.ui.activities.main.SplashScreenActivity;
import com.bdtop.dbl.ui.activities.me.MsgActivity;
import com.bdtop.dbl.ui.view.SelectDialog;
import com.bdtop.dbl.ui.view.TitleBar;
import com.bdtop.dbl.ui.view.SelectDialog.DialogInterfaceListener;
import com.bdtop.dbl.utils.Constants;
import com.bdtop.dbl.utils.DBLDebug;
import com.bdtop.dbl.utils.ImageUtils;
import com.bdtop.dbl.utils.NetworkUtils;
import com.bdtop.dbl.utils.Preferences;

import java.io.File;

/**
 * @ClassName: ModifyInfoActivity
 * @Description: TODO
 * @author: liyongqiang
 * @date:2014-10-24
 */
@SuppressLint("SdCardPath")
public class DeviceInfoActivity extends BaseActivity implements OnClickListener {

	private TitleBar mTitleBar;
	private TextView txImei, txMac, txNickname, txUpdateNickname, txSim;
	private TextView txLocationMode, txElec, txState, txLocation, txSosPhones;
	private View layoutModiLocationMode, layoutModiSosPhones, layoutMac;
	private Button btnMsg, btnFence, btnPower;
	private View layoutDataPart;
	private Button btnUpdateHend;
	private ImageView deviceImg;
	private ProgressBar progressBar;

	int currentState;
	int currentMode;
	String[] lMode;

	public static final void launch(Context context, DeviceInfo device) {
		Intent intent = new Intent(context, DeviceInfoActivity.class);
		intent.putExtra(Constants.INTENT_DEVICE, device);
		context.startActivity(intent);
		((Activity) context).overridePendingTransition(R.anim.slide_in_right, R.anim.keep_original_state);
	}

	private DeviceInfo device;

	@Override protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_modi_info);
		super.onCreate(savedInstanceState);
		device = (DeviceInfo) getIntent().getSerializableExtra(Constants.INTENT_DEVICE);

		mSearch = GeoCoder.newInstance();
		initViews();

		String mac = "";
		if (device != null) {
			mac = Preferences.getMacForImei(this, device.imei);
		}

		if (!TextUtils.isEmpty(mac)) {
			// layoutMac.setVisibility(View.VISIBLE);
			txMac.setText(mac);
		} else {
			// layoutMac.setVisibility(View.GONE);
			txMac.setText(R.string.click_to_bind_mac);
			txMac.setTextColor(Color.parseColor("#FF4444"));
		}

	}

	@Override protected void onResume() {
		super.onResume();
		if (DBLApplication.getInstance().deviceInfoList != null && device != null) {
			DeviceInfo mdi = null;
			for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
				if (device.mdn.equals(di.mdn)) {
					mdi = di;
					break;
				}
			}
			if (mdi != null) {
				updateUI(mdi);
			}
		}

	}

	private void updateUI(DeviceInfo device) {
		if (device == null) {
			return;
		}
		layoutDataPart.setVisibility(View.VISIBLE);

		txImei.setText(device.imei);
		txSim.setText(device.mdn);
		// txMac.setText(device.device_mac);

		currentMode = device.location_mode;
		lMode = getResources().getStringArray(R.array.device_location_mode);
		if (currentMode > lMode.length || currentMode < 1)
			currentMode = 1;
		txLocationMode.setText(lMode[currentMode - 1]);

		if (DBLApplication.getInstance().currentDi.elec > 100 || DBLApplication.getInstance().currentDi.elec < 0) {
			txElec.setText(getString(R.string.unkown));
		} else {
			txElec.setText(device.elec + getString(R.string.percent));
		}

		/* 用power判断 */
		String power = device.power;
		// currentState = device.state;
		currentState = power.equals("on") ? 1 : 2;
		String[] dState = getResources().getStringArray(R.array.device_state);
		if (currentState > dState.length || currentState < 1)
			currentState = 1;
		txState.setText(dState[currentState - 1]);
		
		String addressName = null ; 
		if(DBLApplication.getInstance().deviceInfoList != null){
			for (DeviceInfo di : DBLApplication.getInstance().deviceInfoList) {
				if(device.mdn.equals(di.mdn)){
					if(di.pos != null && di.pos.addrname != null && !"null".equals(di.pos.addrname )){
						addressName = di.pos.addrname ;
						break;
					}
				}
			}
		}
		
//		if(TextUtils.isEmpty(addressName)){
//			addressName = DBLApplication.getInstance().getAddressInfoByMdn(device.mdn);
//			if (TextUtils.isEmpty(addressName)) {
//				txLocation.setText(Constants.EMPTY_ADDRESS_INFO);
//				if (device.pos != null) {
//					requestDeviceAddressInfo(txLocation, device.pos.lon, device.pos.lat
//							, device.mdn);
//				}
//			} else {
//				txLocation.setText(addressName);
//			}
//		} else {
//			txLocation.setText(addressName);
//		}
		
		if (device.pos != null) {
			txLocation.setText(Constants.EMPTY_ADDRESS_INFO);
			requestDeviceAddressInfo(txLocation , device.pos.lon, device.pos.lat
					, device.mdn);
		} else {
			txLocation.setText(Constants.ERROR_ADDRESS_INFO);
		}
		
		String[] arrayPhones = device.sos_phones;
		String mPhones = getString(R.string.none_sos_phones);
		if (arrayPhones != null && arrayPhones.length > 0) {
			mPhones = "";
			for (int i = 0; i < arrayPhones.length; i++) {
				mPhones += "\n" + arrayPhones[i];
			}
			mPhones = mPhones.substring("\n".length());
		}
		txSosPhones.setText(mPhones);

	}

	private void setBtnPower(boolean showClose) {
		if (showClose) {
			btnPower.setText(R.string.modify_info_button_6_2);
			btnPower.setBackgroundResource(R.color.transparent);
			btnPower.setOnClickListener(null);
			// btnPower.setLayoutParams(
			// new LayoutParams(LayoutParams.WRAP_CONTENT,
			// LayoutParams.WRAP_CONTENT));
			handler.sendEmptyMessageDelayed(MSG_POWER_ON, 60 * 1000);
		} else {
			btnPower.setText(R.string.modify_info_button_6);
			btnPower.setBackgroundResource(R.drawable.selector_oval_red_bg);
			btnPower.setOnClickListener(this);
		}
	}

	private final int MSG_POWER_ON = 32;
	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (MSG_POWER_ON == msg.what) {
				setBtnPower(false);
			}
		};
	};

	@Override protected void onDestroy() {
		super.onDestroy();
		handler.removeMessages(MSG_POWER_ON);
		mSearch.destroy();
	};

	private void initViews() {
		mTitleBar = (TitleBar) findViewById(R.id.title_bar);
		mTitleBar.setTitle(R.string.modify_info_title);
		mTitleBar.setBelongActivity(this);

		// deviceTitle = (TextView) findViewById(R.id.device_title);
		txImei = (TextView) findViewById(R.id.tv_imei);
		txMac = (TextView) findViewById(R.id.tv_mac);
		txSim = (TextView) findViewById(R.id.tv_sim);

		txNickname = (TextView) findViewById(R.id.nickname);
		txUpdateNickname = (TextView) findViewById(R.id.update_nickname);

		txLocationMode = (TextView) findViewById(R.id.tx_location_mode);
		txElec = (TextView) findViewById(R.id.tx_elec);
		txState = (TextView) findViewById(R.id.tx_state);
		txLocation = (TextView) findViewById(R.id.tx_location);
		txSosPhones = (TextView) findViewById(R.id.tx_sos_phones);

		layoutModiLocationMode = findViewById(R.id.layout_modi_location_mode);
		layoutModiLocationMode.setOnClickListener(this);
		layoutModiSosPhones = findViewById(R.id.layout_modi_sos_phones);
		layoutModiSosPhones.setOnClickListener(this);

		layoutMac = findViewById(R.id.layout_mac);
		layoutMac.setOnClickListener(this);

		btnMsg = (Button) findViewById(R.id.btn_msg);
		btnFence = (Button) findViewById(R.id.btn_fence);
		btnPower = (Button) findViewById(R.id.btn_power);

		btnMsg.setOnClickListener(this);
		btnFence.setOnClickListener(this);
		btnPower.setOnClickListener(this);

		btnUpdateHend = (Button) findViewById(R.id.btn_update_hend);
		btnUpdateHend.setOnClickListener(this);

		deviceImg = (ImageView) findViewById(R.id.device_img);
		progressBar = (ProgressBar) findViewById(R.id.progressBar);

		if (device != null) {
			txNickname.setText(device.name);
		}

		txUpdateNickname.setOnClickListener(this);

		layoutDataPart = findViewById(R.id.layout_data_part);
		layoutDataPart.setVisibility(View.GONE);
		txWaitingMessage = (TextView) findViewById(R.id.tx_waiting_message);

		setDeviceHeadImg();
	}

	private void setDeviceHeadImg() {
		String imgid = "";
		if (device != null) {
			imgid = device.imei;
		}
		String localBase64 = Preferences.getDeviceImgBase64(this, imgid);
		Bitmap localBitmap = null;
		if ("".equals(localBase64)) {
			Bitmap defaultImg = ImageUtils.toRoundBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.default_device_head));
			deviceImg.setImageBitmap(defaultImg);

			requestHead();
		} else {
			localBitmap = ImageUtils.base64ToBitmap(localBase64.replaceAll(getResources().getString(R.string.add_mark), "+"));
			deviceImg.setImageBitmap(ImageUtils.toRoundBitmap(localBitmap));
		}

	}

	private void requestHead() {
		if (device == null) {
			return;
		}
		final String imgid = device.imei;
		ServerApiFactory.getApiImpl().getImg(loginSign, imgid, new RequestCallback() {

			@Override public void onSuccess(String rawData, Object response) {
				GetImgResponse getImgResponse = (GetImgResponse) response;
				String base64 = "";

				if (getImgResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					if (null != getImgResponse.getImgdata() && !"".equals(getImgResponse.getImgdata())) {
						Preferences.saveDeviceImg(DeviceInfoActivity.this, getImgResponse.getImgdata(), imgid);
						// Preferences.saveDeviceImgName(DeviceInfoActivity.this,
						// getImgResponse.getImgname(), device.mdn);
						base64 = getImgResponse.getImgdata();

						Bitmap bm = null;
						try {
							bm = ImageUtils.base64ToBitmap(base64.replaceAll(getResources().getString(R.string.add_mark), "+"));
						} catch (Exception e) {
						}
						if (null != bm) {
							deviceImg.setImageBitmap(ImageUtils.toRoundBitmap(bm));
						}
					}
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				// deviceImg.setImageBitmap(defaultImg);
			}
		});
	}

	@Override public void onClick(View view) {
		switch (view.getId()) {
		case R.id.update_nickname:
			showModiDialog();
			break;
		case R.id.btn_msg:
			MsgActivity.launch(this,device.mdn );
			break;
		case R.id.btn_fence:
			FenceListActivity.launch(this, device.mdn);
			break;
		case R.id.btn_power:
			showModiDevicePowerDialog();
			break;
		case R.id.layout_modi_location_mode:
			showModiLocationModeDialog();
			break;
		case R.id.layout_modi_sos_phones:
			DeviceModiPhonesActivity.launch(this, device);
			break;
		case R.id.btn_update_hend:
			SelectDialog dialog = new SelectDialog(this, new DialogInterfaceListener() {

				@Override public void photoListener(Dialog mDialog) {
					getImageFromAlbum();
				}

				@Override public void cameraListener(Dialog mDialog) {
					getImageFromCamera();
				}
			});
			dialog.show();
			break;

		case R.id.layout_mac:
			Preferences.saveRebindImei(DeviceInfoActivity.this, device.imei);
			MainActivity.launch(DeviceInfoActivity.this, MainActivity.ACTION_BLE_RESEARCH); // param
																							// work
			break;
		}
	}

	int REQUEST_CODE_IMAGE_FORM_ALBUM = 1;
	int REQUEST_CODE_IMAGE_FROM_CAMERA = 2;
	int REQUEST_CODE_IMAGE_FROM_CROP = 3;

	String tempPhotoName = "userHead.jpg";

	protected void getImageFromCamera() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FORM_ALBUM);
	}

	protected void getImageFromAlbum() {
		// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("/sdcard/" + tempPhotoName)));
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CAMERA);
	}

	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, REQUEST_CODE_IMAGE_FROM_CROP);
	}

	private String photoPath;
	private Bitmap photo;

	@Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {

			if (requestCode == REQUEST_CODE_IMAGE_FORM_ALBUM) {
				startPhotoZoom(data.getData());
			} else if (requestCode == REQUEST_CODE_IMAGE_FROM_CAMERA) {
				photoPath = "/sdcard/" + tempPhotoName;
				File temp = new File(photoPath);
				startPhotoZoom(Uri.fromFile(temp));
			} else if (requestCode == REQUEST_CODE_IMAGE_FROM_CROP) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					photo = extras.getParcelable("data");
				} else {
					Toast.makeText(this, R.string.tailoring_error, Toast.LENGTH_SHORT).show();
				}
			}
		}

		if (null != photo) {
			photo = ImageUtils.compressImage(photo);
			final String imgid = device.imei;
			final String imgData = ImageUtils.bitmapToBase64(null, photo).replace("+", getResources().getString(R.string.add_mark));

			modiDeviceHead(imgid, imgData);

			progressBar.setVisibility(View.VISIBLE);
			deviceImg.setVisibility(View.GONE);
		}
	}

	private void modiDeviceHead(final String imgid, final String imgData) {
		ServerApiFactory.getApiImpl().updateImgRequest(loginSign, imgid, imgData, new RequestCallback() {

			@Override public void onSuccess(String rawData, Object response) {
				BaseResponse baseResponse = (BaseResponse) response;
				if (baseResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					deviceImg.setImageBitmap(ImageUtils.toRoundBitmap(photo));
				}
				showToast(baseResponse.getDesc());
				progressBar.setVisibility(View.GONE);
				deviceImg.setVisibility(View.VISIBLE);
				photo = null;

				Preferences.saveDeviceImg(DeviceInfoActivity.this, imgData, imgid);
				// Preferences.saveDeviceImgName(DeviceInfoActivity.this,
				// imgName,
				// device.mdn);

			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
				progressBar.setVisibility(View.GONE);
				deviceImg.setVisibility(View.VISIBLE);
				photo = null;
			}
		});
	}

	private Dialog mDialog;

	private void showModiLocationModeDialog() {
		View content = LayoutInflater.from(this).inflate(R.layout.dialog_device_location_mode_2, null);
		content.findViewById(R.id.tx_mode_1).setOnClickListener(onModeChangeListener);
		content.findViewById(R.id.tx_mode_2).setOnClickListener(onModeChangeListener);
		content.findViewById(R.id.tx_mode_3).setOnClickListener(onModeChangeListener);

		showDialog(content, true, true);
	}

	OnClickListener onModeChangeListener = new OnClickListener() {
		@Override public void onClick(View view) {

			switch (view.getId()) {
			case R.id.tx_mode_1:
				currentMode = 1;
				break;
			case R.id.tx_mode_2:
				currentMode = 2;
				break;
			case R.id.tx_mode_3:
				currentMode = 3;
				break;
			}
			dismissDialog();

			toModiLocationMode();
		}
	};

	private void toModiLocationMode() {
		txWaitingMessage.setVisibility(View.VISIBLE);
		txWaitingMessage.setText(R.string.wating_update);

		String mdn = device.mdn;

		ServerApiFactory.getApiImpl().deviceModi(loginSign, mdn, null, null, currentMode, null, new RequestCallback() {
			@Override public void onSuccess(String rawData, Object response) {
				txWaitingMessage.setVisibility(View.GONE);
				BaseResponse br = (BaseResponse) response;
				showToast(br.getDesc());
				if (br.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					showToast(R.string.oper_success);
					txLocationMode.setText(lMode[currentMode - 1]);
					if (DBLApplication.getInstance().deviceInfoList != null && device != null) {
						for (DeviceInfo d : DBLApplication.getInstance().deviceInfoList) {
							if (d.mdn.equals(device.mdn)) {
								d.location_mode = currentMode;
								break;
							}
						}
					}
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				txWaitingMessage.setVisibility(View.GONE);
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}

	public void showDialog(View content, boolean canCancel, boolean shadow) {
		dismissDialog();

		mDialog = new Dialog(this, shadow ? R.style.Theme_Light_NoTitle_Dialog : R.style.Theme_Light_NoTitle_NoShadow_Dialog);

		mDialog.setContentView(content);
		mDialog.setCanceledOnTouchOutside(canCancel);
		mDialog.setCancelable(canCancel);
		mDialog.show();
	}

	public void dismissDialog() {
		if (mDialog != null && mDialog.isShowing())
			mDialog.dismiss();
		mDialog = null;
	}

	private void showModiDevicePowerDialog() {
		View content = LayoutInflater.from(this).inflate(R.layout.dialog_confirm_2, null);
		((TextView) content.findViewById(R.id.tx_message)).setText(R.string.guanjiTip);
		OnClickListener listener = new OnClickListener() {
			@Override public void onClick(View arg0) {
				if (arg0.getId() == R.id.btn_confirm) {
					modiDevicePower();
				}
				dismissDialog();
			}
		};
		content.findViewById(R.id.btn_confirm).setOnClickListener(listener);
		content.findViewById(R.id.btn_cancel).setOnClickListener(listener);

		showDialog(content, true, true);
	}

	private void modiDevicePower() {
		final boolean power = false;
		txWaitingMessage.setVisibility(View.VISIBLE);
		txWaitingMessage.setText(R.string.wating_update);
		String sign = Preferences.getLoginSign(this);
		String mdn = "";
		if (device != null) {
			mdn = device.mdn;
		}
		ServerApiFactory.getApiImpl().deviceModi(sign, mdn, null, power, null, null, new RequestCallback() {

			@Override public void onSuccess(String rawData, Object response) {
				txWaitingMessage.setVisibility(View.GONE);

				BaseResponse baseResponse = (BaseResponse) response;
				showToast(baseResponse.getDesc());
				if (baseResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					showToast(R.string.oper_success);
					setBtnPower(true);

					for (DeviceInfo d : DBLApplication.getInstance().deviceInfoList) {
						if (d.mdn.equals(device.mdn)) {
							d.power = power ? "on" : "off";
							break;
						}
					}
				}

			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				txWaitingMessage.setVisibility(View.GONE);
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}

	@Override public void finish() {
		super.finish();
		overridePendingTransition(R.anim.keep_original_state, R.anim.slide_out_right);
	}

	/************** update name ****************/
	private Dialog modiDialog;

	private void showModiDialog() {
		View content = LayoutInflater.from(this).inflate(R.layout.dialog_modi2, null);
		TextView txTitle = (TextView) content.findViewById(R.id.tx_title);
		txTitle.setText(R.string.modify);

		final EditText edText = (EditText) content.findViewById(R.id.ed_text);
		edText.setHint(R.string.hint_modi_nickname);
		InputFilter[] filters = { new LengthFilter(16) };
		edText.setFilters(filters);
		content.findViewById(R.id.btn_ok).setOnClickListener(new OnClickListener() {
			@Override public void onClick(View arg0) {
				String value = edText.getText().toString().trim();
				if (TextUtils.isEmpty(value)) {
					showToast(R.string.nickname_format_2);
				} else if (!value.matches(Constants.VALIDATE_NAME)) {
					showToast(R.string.validate_1);
				} else {
					requestModiNickName(value);
					dismissModiDialog();
				}
			}
		});

		modiDialog = new Dialog(this, R.style.Theme_Light_NoTitle_Dialog);

		modiDialog.setContentView(content);
		modiDialog.setCanceledOnTouchOutside(true);
		modiDialog.setCancelable(true);
		modiDialog.show();
	}

	private void dismissModiDialog() {
		if (modiDialog != null && modiDialog.isShowing())
			modiDialog.dismiss();
		modiDialog = null;
	}

	private void requestModiNickName(final String value) {
		setAndShowWaitingMessage(R.string.wating_update);
		ServerApiFactory.getApiImpl().deviceModi(loginSign, device.mdn, value, null, null, null, new RequestCallback() {
			@Override public void onSuccess(String rawData, Object response) {
				clearAndHiddenWaitingMessage();
				BaseResponse baseResponse = (BaseResponse) response;
				showToast(baseResponse.getDesc());
				if (baseResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					txNickname.setText(value);

					if (DBLApplication.getInstance().deviceInfoList != null && device != null) {
						for (DeviceInfo d : DBLApplication.getInstance().deviceInfoList) {
							if (d.mdn.equals(device.mdn)) {
								d.name = value;
								break;
							}
						}
					}
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
				clearAndHiddenWaitingMessage();
			}
		});
	}

	// 2015  api  从服务器获得 车联网地址信息
	@Deprecated private void requestDeviceAddressInfo(double lon, double lat) {
		if (device == null) {
			return;
		}
		DBLDebug.logd("请求设备" + device.name + "的地址信息:");
		ServerApiFactory.getApiImpl().getAddressInfo(loginSign, lon, lat, new RequestCallback() {
			@Override public void onSuccess(String rawData, Object response) {
				AddressResponse addressResponse = (AddressResponse) response;
				if (addressResponse.getStatus().equals(Constants.REQUEST_SUCCESS)) {
					String address = addressResponse.addrname;
					DBLDebug.logd("请求地址信息结果：" + address);
					if (!TextUtils.isEmpty(address)) {
						txLocation.setText(address);
						if (device != null && device.mdn != null) {
							DBLDebug.logd("存储设备" + device.name + "的地址信息至Application中");
							DBLApplication.getInstance().setAddressInfoByMdn(device.mdn, address);
						}
					}
				}
			}

			@Override public void onError(int statusCode, Throwable e, String rawData) {
				if (NetworkUtils.isNetConnect(getApplicationContext())) {
					showToast(R.string.oper_error);
				} else {
					showToast(R.string.net_error);
				}
			}
		});
	}
	
	GeoCoder mSearch = null;
	// 2015  api  从【百度】服务器获得 百度地址信息
	private void requestDeviceAddressInfo(final TextView txInfo, double lon, double lat,final String mdn) {
		LatLng ptCenter = new LatLng(lat, lon);
		mSearch.reverseGeoCode(new ReverseGeoCodeOption()
				.location(ptCenter));
		mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
			@Override public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
				if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
					Log.e("LocationFragmet", "onGetReverseGeoCodeResult 抱歉未能找到结果");
					return;
				}
				String info = result.getAddress();
				txInfo.setText(info);
				DBLDebug.logd("存储设备:[" + mdn + "]地址信息 ["+info+"]至Application中");
				DBLApplication.getInstance().setAddressInfoByMdn(mdn, info);
			}
				
			@Override public void onGetGeoCodeResult(GeoCodeResult result) {
				if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
					Log.e("LocationFragmet", "onGetGeoCodeResult 抱歉未能找到结果");
					return;
				}
				String strInfo = String.format("纬度：%f 经度：%f",
						result.getLocation().latitude, result.getLocation().longitude);
				Log.e("LocationFragmet", strInfo);
			}
		});
	}
}
